//
//  LSLoginVController.m
//  LookScore
//
//  Created by wr on 2017/12/5.
//  Copyright © 2017年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSLoginVController.h"
#import "UIView+Extension.h"
#import "LSLoginInputCell.h"
#import "LSRegisterVController.h"
#import "LSForgetPasswardVController.h"
#import "LSHttpEnclosureTool.h"
#import "LSAccountCoder.h"
#import "LSAccountArchive.h"
#import "NSString+JKNormalRegex.h"
#import "MBProgressHUD+MJ.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
#import "LSPhoneVerificationVController.h"
#import "AppDelegate.h"
#import "LSHttpTool.h"
#import <IQKeyboardManager.h>
#import "LSNavigationViewController.h"
@interface LSLoginVController ()<UITableViewDelegate,UITableViewDataSource,TencentLoginDelegate,TencentSessionDelegate,TencentWebViewDelegate,ADelegate>

@property(strong,nonatomic)UITableView *tableView;

@property(strong,nonatomic)NSArray *imgArray;

@property(copy,nonatomic)NSString *userNameString;

@property(copy,nonatomic)NSString *passwordString;

@property(assign,nonatomic)BOOL selectRememberKey;
@property(nonatomic, strong) UITextField *  userNameTF;
@property (nonatomic, strong) UITextField * passWordTF;
@property (nonatomic, strong) TencentOAuth * tencentOAuth;
@end

@implementation LSLoginVController{
    
    
//    TencentOAuth * _tencentOAuth;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor =LSBackGroundColor;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled=NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"登录";
    
    self.selectRememberKey = [[NSUserDefaults standardUserDefaults] boolForKey:@"select"];
    self.userNameString = [[NSUserDefaults standardUserDefaults] objectForKey:@"userNameString"];
    self.passwordString = [[NSUserDefaults standardUserDefaults] objectForKey:@"passwordString"];
    
    self.view.backgroundColor=LSTitleWhiteColor;
    [self.navigationController.navigationBar setBackgroundImage:[CommonClass getImageWithBgColor:LSNavMainColor] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];

    self.imgArray=@[@[@"RegisterPhone",@"请输入手机号码"],@[@"RegistLock",@"请输入6~15位密码"]];
    
    UIImageView *topImgView=[[UIImageView alloc]init];
    topImgView.image=[UIImage imageNamed:@"LoginTop"];
    [self.view addSubview:topImgView];
    topImgView.sd_layout.leftEqualToView(self.view).topEqualToView(self.view).rightEqualToView(self.view).heightIs(LSAutoVlaue(80, LSScreenHeight));
    
    
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.leftEqualToView(self.view).topSpaceToView(topImgView,LSAutoVlaue(30, LSScreenHeight)).rightEqualToView(self.view).bottomEqualToView(self.view);
    [notifiCenter addObserver:self selector:@selector(managerDidRecvAuthResponse:) name:@"threeLoginSuccess" object:nil];
}



#pragma mark 🔥 tableViewDelegate tableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row!=2) {
        return LSControlHeight;
    }
    return self.tableView.height-LSControlHeight*2;
    
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row<2) {
        
        LSLoginInputCell *cell=[LSLoginInputCell loginInputTableViewCellByTableView:tableView];
        cell.inputImg.image=[UIImage imageNamed:self.imgArray[indexPath.row][0]];
     
        
        
        if (indexPath.row==0) {
            cell.inputTF.keyboardType=UIKeyboardTypePhonePad;
            cell.inputTF.text = self.userNameString;
            cell.eysBtn.hidden=YES;
            _userNameTF = cell.inputTF;
        }
        if (indexPath.row==1) {
            cell.inputTF.keyboardType=UIKeyboardTypeASCIICapable;
            cell.inputTF.secureTextEntry = YES;
            cell.inputTF.text = self.passwordString;
            cell.eysBtn.hidden=NO;
            _passWordTF = cell.inputTF;
            cell.isEyesOpenedBlock = ^(UIButton *sender) {
                sender.selected=!sender.selected;
                _passWordTF.secureTextEntry = !sender.selected;
                
            };
//            cell.isEyesOpenedBlock = ^{
//                MyLog(@"显示密码按钮");
//            };
        }
        
        [cell.inputTF addTarget:self action:@selector(getTextString:) forControlEvents:UIControlEventEditingChanged];
        cell.inputTF.placeholder=self.imgArray[indexPath.row][1];
        cell.inputTF.tag = indexPath.row;
        
        return cell;
    }else{
        LSLoginEventCell *cell=[LSLoginEventCell loginEventTableViewCellByTableView:tableView];
        cell.LoginOrRegisterOrForgetKeyBlock = ^(KLoginOrRegisterOrForgetKeyType type) {
            [self LoginOrRegisterOrForgetKeyAction:type];
        };
        cell.clickRememberKeyButtonBlock = ^(BOOL selectOrNot) {
            self.selectRememberKey = selectOrNot;
        };
    
        return cell;
    }
    return nil;
}
- (void)getTextString:(UITextField *)textField{
    if (textField.tag == 0) {
        self.userNameString = textField.text;
    }
    if (textField.tag == 1) {
        self.passwordString = textField.text;
    }
    MyLog(@"textField ----- %@",textField.text);
}

#pragma mark 🔥 LoginOrRegisterAction
-(void)LoginOrRegisterOrForgetKeyAction:(KLoginOrRegisterOrForgetKeyType )type{
  
    switch (type) {
        case KLoginOrRegisterOrForgetKeyIsLogin :
            
            [self goToLogin];
            break;
            
        case KLoginOrRegisterOrForgetKeyIsRegister :{
//            去注册
            LSRegisterVController *registerVC=[[LSRegisterVController alloc]init];
            registerVC.registeSuccessBlock = ^{
                self.userNameString = [[NSUserDefaults standardUserDefaults] objectForKey:@"userNameString"];
                [self.tableView reloadData];
            };
            [self.navigationController pushViewController:registerVC animated:YES];
        }
            break;
        case KLoginOrRegisterOrForgetKeyIsForget :{
            
            LSForgetPasswardVController *forgetVC=[[LSForgetPasswardVController alloc]init];
            [self.navigationController pushViewController:forgetVC animated:YES];
        }
            break;
        case KLoginOrRegisterOrForgetKeyIsQQLogin :
            [self startThirdLoginAboutType:KLoginOrRegisterOrForgetKeyIsQQLogin];
            break;
        case KLoginOrRegisterOrForgetKeyIsWXLogin :
            [self startThirdLoginAboutType:KLoginOrRegisterOrForgetKeyIsWXLogin];
            break;
            
        default:
            break;
    }
}




#pragma mark 🔥 普通登录
-(void)goToLogin{
    
    if (![self.userNameString jk_isMobileNumber]) {
        [MBProgressHUD showOnlyMessage:@"请输入有效手机号" afterDelay:1.5f];
    }else if(self.passwordString.length == 0){
        [MBProgressHUD showOnlyMessage:@"请输入密码" afterDelay:1.5f];
        
    }
    else if ([self isEmpty:self.passwordString]) {
        [MBProgressHUD showOnlyMessage:@"密码中不能含有空格字符" afterDelay:1.5f];
    }
    
    else{
        [[NSUserDefaults standardUserDefaults] setObject:self.userNameString forKey:@"userNameString"];
        if (self.selectRememberKey) {
            MyLog(@"记住密码");
            [[NSUserDefaults standardUserDefaults] setObject:self.passwordString forKey:@"passwordString"];
            [[NSUserDefaults standardUserDefaults] setBool:self.selectRememberKey forKey:@"select"];
            
        }else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passwordString"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"select"];
        }
        
        NSDictionary *loginDic = @{@"mobile":self.userNameString,@"pwd":self.passwordString};
        [self loginNetWork: loginDic];
    }
}

-(BOOL)isEmpty:(NSString *) str {
    NSRange range = [str rangeOfString:@" "];
    if (range.location != NSNotFound) {
        return  YES; //yes代表包含空格
    }else {
        return  NO;  //反之
    }
}
- (void)loginNetWork:(NSDictionary *)loginDic{
    [LSHttpEnclosureTool POST:LSUserLogin parameters:loginDic resBlock:^(id responseObject) {
        MyLog(@"%@",responseObject);
        if (responseObject) {
            NSString *cidStr=(NSString *)responseObject;
            [LSHttpEnclosureTool GET:LSUserInfo parameters:@{@"cid":cidStr} resBlock:^(id responseObject) {
                MyLog(@"userInfo:%@",responseObject);
                if (responseObject) {
                    
                    LSAccountCoder *coderModel=[LSAccountCoder mj_objectWithKeyValues:responseObject];
                    [LSAccountArchive saveAccount:coderModel];
                    
                    [notifiCenter postNotificationName:@"LOGINSUCCESS" object:nil];
                    
//                    JANALYTICSLoginEvent * event = [[JANALYTICSLoginEvent alloc] init];
//                    
//                    event.success = YES;
//                    
//                    event.method = @"login type";
//                    
//                    event.extra = @{@"custom key1":@"custom value"};
//                    
//                    [JANALYTICSService eventRecord:event];
                    
                    if (self.loginSuccessBlock) {
                        self.loginSuccessBlock();
                    }
                    [self dismissViewController];
                }
            }];
        }
    }];
}
#pragma mark 🔥 第三方登录
- (void)startThirdLoginAboutType:(KLoginOrRegisterOrForgetKeyType )type{
    if (type == KLoginOrRegisterOrForgetKeyIsQQLogin) {
        
//        LSPhoneVerificationVController * phoneVerificationVc = [[LSPhoneVerificationVController alloc] init];
//        [self.navigationController pushViewController:phoneVerificationVc animated:YES];
        
        self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"101489380" andDelegate:self];
        self.tencentOAuth.authShareType = AuthShareType_QQ;
        NSArray *permissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil];
        [self.tencentOAuth authorize:permissions];
    }else{
        if ([WXApi isWXAppInstalled]) {
            SendAuthReq * req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact";
            req.state = @"com.lookScore.Lottery";
            req.openID = @"wxb36fec60af8a29dd";//这个地方写你申请的APPID"
            
            [WXApi sendReq:req];
        }else{
            
            
        }
    }
    
}
#pragma mark -- qq登录回调
- (void)tencentDidLogin{
    
    MyLog(@"%@ -- %@ -- %@",_tencentOAuth.accessToken, _tencentOAuth.openId,_tencentOAuth.unionid);
    [self.tencentOAuth getUserInfo];
//    [self.tencentOAuth openId];
    
}

- (void)tencentDidNotLogin:(BOOL)cancelled{
    
    if (cancelled) {
        
    }
    
}

- (void)tencentDidNotNetWork{
    
    
    
}


- (void)getUserInfoResponse:(APIResponse *)response{
    MyLog(@"%@",response);
    
    if (response && response.retCode == URLREQUEST_SUCCEED) {
        NSDictionary *dic = [response jsonResponse];
        [self userLoginCheckWithUnionId:_tencentOAuth.openId withHeadUrl:dic[@"figureurl_qq_2"] withDisName:dic[@"nickname"] withRegType:1];
        
    }else{
        
        MyLog(@"获取用户信息失败");
        
    }
   
    
    
}

#pragma mark appdelegate(微信回调)

- (void)managerDidRecvAuthResponse:(NSNotification *)response{
    SendAuthResp * resp = (SendAuthResp *)response.object;
    NSString * code = resp.code;
//    APPID：我们在微信开发平台申请的APPID
//    SECRET：我们在微信开放平台申请的APPSecret
//    CODE:微信授权后获取的code
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxb36fec60af8a29dd",@"2839e9c31a12273f845e6e951d78e4f8",code];
    
//    [LSHttpEnclosureTool]
    [LSHttpTool GETNormarData:urlStr parameters:nil success:^(id responseObject) {
//        MyLog(@"%@",responseObject);
        if (responseObject) {
             NSDictionary * dict = (NSDictionary *)responseObject;
            if (dict[@"access_token"] && [dict[@"access_token"] length] != 0) {
                //            [self refreshTokenWith:@"wxb36fec60af8a29dd" withRefreshToken:dict[@"refresh_token"]];
                [self getWxUserInfomationWith:dict[@"access_token"] withOpenId:dict[@"openid"]];
            }else{
                
//                [MBProgressHUD showOnlyMessage:<#(NSString *)#> afterDelay:<#(NSTimeInterval)#>]
            }

        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)refreshTokenWith:(NSString *)appId withRefreshToken:(NSString *)refreshToken{
    
   //请求的url  不需要改变，只需要把参数换成你们的就行
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",appId,refreshToken];
    //注意：这个地方使用的是刷新授权token而不是token
    [LSHttpEnclosureTool GET:urlStr parameters:nil resBlock:^(id responseObject) {
        
    }];
    
}

- (void)getWxUserInfomationWith:(NSString *)token withOpenId:(NSString *)openId{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token, openId];
    [LSHttpTool GETNormarData:urlStr parameters:nil success:^(id responseObject) {
        MyLog(@"----%@",responseObject);
        if (responseObject) {
            
            NSDictionary *dic = (NSDictionary *)responseObject;
            if (dic[@"unionid"] && [dic[@"unionid"] length] != 0) {
                [self userLoginCheckWithUnionId:dic[@"unionid"] withHeadUrl:dic[@"headimgurl"] withDisName:dic[@"nickname"] withRegType:2];
            }else{
               [self refreshTokenWith:@"wxb36fec60af8a29dd" withRefreshToken:token];
            }
            
        }
    } failure:^(NSError *error) {
        
    }];
//    [LSHttpEnclosureTool GET:urlStr parameters:nil resBlock:^(id responseObject) {
//
//
//
//    }];
}


#pragma mark -- 判断用户是否是首次三方登录

- (void)userLoginCheckWithUnionId:(NSString *)opendId withHeadUrl:(NSString *)headUrl withDisName:(NSString *)disName withRegType:(NSInteger)type{
    
    NSDictionary * dict = @{@"unionId":opendId,@"headUrl":headUrl,@"disName":disName,@"regType":@(type)};
    //判断用户是否首次三方登录
    [LSHttpEnclosureTool POST:LSUserCheck parameters:dict resBlock:^(id responseObject) {
        if (responseObject) {
            LSAccountCoder *coderModel=[LSAccountCoder mj_objectWithKeyValues:responseObject];
            if ([coderModel.Cid isEqualToString:@""] || coderModel.Cid == nil) {
                //为空 调到绑定手机页面
                LSPhoneVerificationVController * phoneVerificationVc = [[LSPhoneVerificationVController alloc] init];
                
                phoneVerificationVc.openId = opendId;
                phoneVerificationVc.headUrl = headUrl;
                phoneVerificationVc.disName = disName;
                phoneVerificationVc.regType = [NSString stringWithFormat:@"%ld",(long)type];
                phoneVerificationVc.block = ^(LSAccountCoder * model) {
//                    LSAccountCoder *coderModel=[LSAccountCoder mj_objectWithKeyValues:responseObject];
                    [LSAccountArchive saveAccount:model];
                    if (self.loginSuccessBlock) {
                        self.loginSuccessBlock();
                    }
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self dismissViewController];
                    });
                    
                };
                [self.navigationController pushViewController:phoneVerificationVc animated:YES];
                
            }else{
                
                LSAccountCoder *coderModel=[LSAccountCoder mj_objectWithKeyValues:responseObject];
                [LSAccountArchive saveAccount:coderModel];
                if (self.loginSuccessBlock) {
                    self.loginSuccessBlock();
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dismissViewController];
                });
                
                
            }
            
        }
    }];
    
}

-(void)dismissViewController{
    
    if ((self.navigationController.presentedViewController || self.navigationController.presentingViewController) && self.navigationController.childViewControllers.count == 1) {
        [_userNameTF resignFirstResponder];
        [_passWordTF resignFirstResponder];
        if ([self.presentVCName isEqualToString:@"chatRoom"]) {
            [notifiCenter postNotificationName:@"ChatKeyboardShouldResignFirstResponder" object:@(1)];
        }else if ([self.presentVCName isEqualToString:@"ConverSationVC"]){

             [notifiCenter postNotificationName:@"ChatKeyboardShouldResignFirstResponder" object:@(2)];
        }

        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
